package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.mapper.PaymentInfoMapper;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 付款信息Service业务层处理
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements IPaymentInfoService {
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Autowired
    private RabbitService rabbitService;


    @Override
    public PaymentInfo savePaymentInfo(String orderNo) {
        //1.查询支付信息
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        if (paymentInfo == null) { //判断也是相当于做了去重处理。
            //2.没保存过支付信息则保存支付信息
            //2.1.根据订单号查询订单信息
            R<OrderInfo> orderInfoResult =
                    remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
            if(orderInfoResult.getCode() == R.FAIL){
                throw new ServiceException(orderInfoResult.getMsg());
            }
            OrderInfo orderInfo = orderInfoResult.getData();

            //2.2封装支付信息
            paymentInfo = new PaymentInfo();
            paymentInfo.setUserId(SecurityContextHolder.getUserId());
            paymentInfo.setOrderNo(orderNo); //商家平台生成订单号
            paymentInfo.setPayType(2); // 付款方式：1-微信 2-支付宝
            paymentInfo.setAmount(orderInfo.getTotalAmount());
            List<OrderItem> orderItemList = orderInfo.getOrderItemList();
            StringBuilder builder = new StringBuilder();
            for (OrderItem orderItem : orderItemList) {
                builder.append(orderItem.getSkuName()+";");
            }
            paymentInfo.setContent(builder.toString());
            paymentInfo.setPaymentStatus("0"); //支付状态：0-未支付 1-已支付 -1-关闭

            //2.3保存支付信息
            paymentInfoMapper.insert(paymentInfo); //主键自动回填
        }
        //3.如果保存过支付信息则直接返回
        return paymentInfo;
    }

    @Override
    public void updatePaymentInfoStatus(Map<String, String> paramMap) {
        String orderNo = paramMap.get("out_trade_no");//支付宝扣款后通过这个参数将商家平台的订单号返回。
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        if(paymentInfo!=null && paymentInfo.getPaymentStatus().equals("0")){
            paymentInfo.setPayType(2); //付款方式：1-微信 2-支付宝
            paymentInfo.setPaymentStatus("1"); //支付状态：0-未支付 1-已支付 -1-关闭
            paymentInfo.setTradeNo(paramMap.get("trade_no")); //支付宝和买家之间产生扣款的交易流水号
            paymentInfo.setCallbackTime(new Date());
            paymentInfo.setCallbackContent(JSON.toJSONString(paramMap));
            paymentInfoMapper.updateById(paymentInfo);

            //基于MQ通知订单系统，修改订单状态
            rabbitService.sendMessage(MqConst.EXCHANGE_PAYMENT_PAY, MqConst.ROUTING_PAYMENT_PAY, paymentInfo.getOrderNo());
        }

    }
}